#!/bin/bash
# 批量推送公钥

# expect是否安装
yum list installed | grep expect
test $? -ne 0 && echo -e "\e[1;31m安装expect\e[0m" && yum -y install expect

# 公钥是否存在
[ ! -f ~/.ssh/id_rsa ] && ssh-keygen -P '' -f ~/.ssh/id_rsa

# 循环判断主机是否ping通，如果ping通推送公钥，IP密码从ip.txt中获取
cat ~/ip.txt|while read ip pass
do
        ping -c1 $ip &>/dev/null
        if [ $? -eq 0 ];then
                echo $ip >> ~/ip_up.txt
                /usr/bin/expect <<-END &>/dev/null
                set timeout 8
                spawn ssh-copy-id root@$ip
                expect {
                        "yes/no" {send "yes\r";exp_continue;}
                        "password:" {send "$pass\r";}
                }
                expect eof
                END
        else
                echo -e "\e[1;31m${ip}ping不通\e[0m"
        fi
done

# 验证是否全部成功
for i in `cat ~/ip_up.txt`;do
        ssh root@$i hostname
        test $? -eq 0 && echo -e "\e[1;32m${i}成功\e[0m"
done
